<?php
// +----------------------------------------------------------------------
// | B5LaravelCMF
// +----------------------------------------------------------------------
// | Author: 李恒 <357145480@qq.com>
// +----------------------------------------------------------------------
namespace App\Services;

use App\Models\AdminRole;

/**
 * 人员权限分组管理
 * Class AdminRoleService
 * @package App\Services
 */
class AdminRoleService extends BaseService
{
    public function __construct(bool $loadValidate = true)
    {
        $this->setModel(new AdminRole());
    }

    public function getList($isgroup=true)
    {
        $map = [];
        $sort = [];
        $order_column = 'id';
        $order_sort = 'asc';
        $page = 1;
        $limit = PAGE_LIMIT;

        $param = request()->input();

        $map1=[];
        if(!empty($param['role_id'])){
            $map1[]=['role_id','=',$param['role_id']];
        }else{
            return message('操作成功', true, [], 0, '', ['total' => 0]);
        }

        //表单的条件 where 的条件
        if (!empty($param['where']) && is_array($param['where'])) {
            foreach ($param['where'] as $paramField => $paramValue) {
                $paramValue = trim($paramValue);
                if ($paramValue !== '') {
                    $map[] = [$paramField, '=', $paramValue];
                }
            }
        }
        //表单的条件 like 的条件
        if (!empty($param['like']) && is_array($param['like'])) {
            foreach ($param['like'] as $paramField => $paramValue) {
                $paramValue = trim($paramValue);
                if ($paramValue !== '') {
                    $map[] = [$paramField, 'like', "%{$paramValue}%"];
                }
            }
        }

        //排序条件
        if (!empty($param['orderByColumn'])) {
            $order_column = trim($param['orderByColumn']);
        }
        if (!empty($param['isAsc'])) {
            $order_sort = trim($param['isAsc']);
        }
        // 分页条件
        if (!empty($param['pageNum'])) $page = intval($param['pageNum']);
        if (!empty($param['pageSize'])) $limit = intval($param['pageSize']);

        $sort || $sort = [[$order_column, $order_sort]];


        $offset = ($page - 1) * $limit;
        $query=(new AdminService())->getModel();
        if($map){
            $query=$query->where($map);
        }


        if($isgroup){
            $query=$query->with('role')->whereHas('role', function ($q) use ($map1) {
                $q->when($map1,function ($qq) use ($map1){
                    $qq->where($map1);
                });
            });
        }else{
            $idList=$this->getUsersByRole($param['role_id']);
            if($idList){
                $query=$query->whereNotIn('id',$idList);
            }
        }

        $count=$query->count();
        $query=$query->offset($offset)->limit($limit);

        if (!empty($sort)) {
            $query = $query->when($sort, function ($q, $sort) {
                foreach ($sort as $v) {
                    $q->orderBy($v[0], $v[1]);
                }
            });
        }
        $list = $query->get();

        if($list){
            $list=$list->toArray();
            if($isgroup){
                foreach ($list as $key=>$value){
                    $value['aid']=$value['id'];
                    $value['id']=$value['role']['id'];
                    unset($value['role']);
                    $list[$key]=$value;
                }
            }
        }

        return message('操作成功', true, $list, 0, '', ['total' => $count]);
    }

    public function add()
    {
        if(IS_POST){
            $input=request()->input();
            $role_id=$input['role_id']??0;
            $user_id=$input['user_id']??'';
            if(!$role_id || !$user_id){
                return message('参数错误',false);
            }
            $user_id=explode(',',trim($user_id));
            $user_id=array_unique($user_id);

            //演示限制
            if(system_isDemo()){
                return $this->demo_system();
            }

            foreach ($user_id as $id){
                if($id){
                    $this->model->add(['admin_id'=>$id,'role_id'=>$role_id]);
                }
            }
            return message('保存成功', true, [], null, 'closeopen_refresh');
        }
        return parent::add(); // TODO: Change the autogenerated stub
    }

    /**
     * 更新信息
     * @param $adminId
     * @param $roleId
     * @return bool
     */
    public function update($adminId, $roleId=''){
        if(empty($adminId)) return false;

        $this->model->drop($adminId,'admin_id');
        if($roleId){
            $structArr=explode(',',$roleId);
            $structArr=array_unique($structArr);
            foreach ($structArr as $id){
                $this->model->add(['admin_id'=>$adminId,'role_id'=>$id]);
            }
        }
        return true;
    }

    /**
     * 获取某个人员的角色列表
     * @param $adminId
     * @param bool $all
     * @param bool $onlyKey
     * @return array
     */
    public function getListByAdmin($adminId,bool $all=true,bool $onlyKey=false){
        $reArr=[];
        if($adminId){
            $list=$this->getAll([['admin_id','=',$adminId]]);

            if($list){
                $RoleService=new RoleService();
                foreach ($list as $value){
                    $roleInfo=$RoleService->info($value['role_id'],true);
                    if($roleInfo){
                        if($all || (!$all && $roleInfo['status'])){
                            if($onlyKey){
                                $reArr[]=$roleInfo['id'];
                            }else{
                                $reArr[]=[
                                    'id'=>$roleInfo['id'],
                                    'name'=>$roleInfo['name']
                                ];
                            }

                        }
                    }
                }
            }
        }
        return $reArr;
    }

    /**
     * 获取某个角色下的所有用户
     * @param $roleId
     * @return array
     */
    public function getUsersByRole($roleId){
        $list=[];
        if($roleId){
            $RoleService=new RoleService();
            $roleInfo=$RoleService->info($roleId,true);
            if($roleInfo){
                $list=$this->getAll([['role_id','=',$roleId]],['admin_id'],[],'admin_id,admin_id');
            }
        }
        return $list?array_unique($list):[];
    }
}
